import java.util.Arrays;
public class MergeSort {
    public static void main(String[] args) {
        int[] elem = {2,1,4,6,9,7,5,8,3};
        //mergeSort(elem,0,elem.length-1);
        System.out.println(Arrays.toString(elem));
        mergeSort(elem);
        System.out.println();
        System.out.println(Arrays.toString(elem));
    }
    //递归实现归并排序
    public static void mergeSort(int[] array,int left,int right){
        if (left >= right){
            return;
        }
        int mid = (left+right)/2;
        mergeSort(array,left,mid);
        mergeSort(array,mid+1,right);
        merge(array,left,right,mid);

    }
    //对排序好的数据进行合并
    public static void merge(int[] array,int start,int end,int mid){
        int s1 = start;
        int s2 = mid+1;
        int[] tmp = new int[end-start+1];
        int k = 0;
        while (s1 <= mid && s2 <= end ){
            if(array[s1] > array[s2]){
                tmp[k++] = array[s2++];
            }else {
                tmp[k++] = array[s1++];
            }
        }
        while (s1 <= mid){
            tmp[k++] = array[s1++];
        }
        while (s2 <= end){
            tmp[k++] = array[s2++];
        }
        for (int i = 0; i < tmp.length; i++) {
            array[i+start] = tmp[i];
        }
    }
    //非递归实现归并排序
    public static void mergeSort(int array[]){
        //对元素进行分组，一组gap个元素
        int gap = 1;
        while (gap < array.length){
            for (int i = 0; i < array.length; i += gap*2) {
                int left = i;
                //mid和right可能会发生越界
                int mid = left + gap - 1;
                if(mid >= array.length){
                    mid =array.length-1;
                }
                int right = mid+gap;
                if(right >= array.length){
                    right = array.length -1;
                }
                merge(array,left,right,mid);
            }
            gap*=2;
        }
    }
}
